package com.zretc.support.service.serviceimpl;

import com.zretc.support.dao.ExampaperDao;
import com.zretc.support.entity.*;
import com.zretc.support.service.ExamPaperService;
import com.zretc.support.service.TopicmultService;
import com.zretc.support.service.TopicsingleService;
import com.zretc.support.tool.ImportExamPaper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ExamPaperServiceImpl implements ExamPaperService {

    @Autowired
    ExampaperDao exampaperDao;
    @Autowired
    TopicsingleService topicsingleService;
    @Autowired
    TopicmultService topicmultService;
    @Autowired
    AnswerServiceImpl asi;

    Logger logger = LoggerFactory.getLogger(ExamPaperServiceImpl.class);

    @Override
    public Exampaper generatePaper(Exampaper exampaper) {
        exampaperDao.save(exampaper);
        return exampaper;
    }

    @Override
    public Exampaper randomGeneratePaper(long courseId, int num1, int num2, int num3, int num4 , int num5) {
        logger.info("courseid:"+courseId);
        Exampaper exampaper = new Exampaper();
        // 判断
        List<Topicsingle> list1 = topicsingleService.getTopicsingleByRand((int)courseId,num1,1).getContent();
        // 填空
        List<Topicsingle> list2 = topicsingleService.getTopicsingleByRand((int)courseId,num2,2).getContent();
        // 综合
        List<Topicsingle> list3 = topicsingleService.getTopicsingleByRand((int)courseId,num3,3).getContent();
        StringBuffer topics = new StringBuffer();
        for (int i = 0; i < list1.size(); i++) {
            topics.append(list1.get(i).getTopicId()).append(",");
        }
        for (int i = 0; i < list2.size(); i++) {
            topics.append(list2.get(i).getTopicId()).append(",");
        }
        for (int i = 0; i < list3.size(); i++) {
            topics.append(list3.get(i).getTopicId()).append(",");
        }
        logger.info("topics:"+topics);
        // 单选
        List<Topicmult> list4 = topicmultService.getTopicmultByRand((int)courseId,num4,1).getContent();
        // 多选
        List<Topicmult> list5 =topicmultService.getTopicmultByRand((int)courseId,num5,2).getContent();

        StringBuffer choose = new StringBuffer();
        for (int i = 0; i < list4.size(); i++) {
            choose.append(list4.get(i).getChooseId()).append(",");
        }
        for (int i = 0; i < list5.size(); i++) {
            choose.append(list5.get(i).getChooseId()).append(",");
        }
        logger.info("choose:"+choose);
        exampaper.setPapertopics(topics+"");
        exampaper.setPaperchoose(choose+"");
        Course course = new Course();
        course.setCourseId((long) courseId);
        exampaper.setCourse(course);
        exampaper = exampaperDao.save(exampaper);
        return exampaper;
    }

    @Override
    public int excelGenerate(Long courseId, MultipartFile file) {
        logger.info("courseid:"+courseId);
        // 封装了一个excel导入的工具类
        ImportExamPaper importExamPaper = new ImportExamPaper();
        try {
            //添加到试卷表中的试题组字符串
            StringBuffer topics = new StringBuffer();
            //添加到选择题表中的选择题组字符串
            StringBuffer choose = new StringBuffer();
            // 这个工具类的方法参数还没有写 -- 需要课程编号和文件的 请根据需要进行修改
            Map map = importExamPaper.importExamPaper(courseId,file);
            //选择
            List<Topicmult> list = (List<Topicmult>) map.get(1);
            for (Topicmult t:list) {
                t = topicmultService.addTopicmult(t);
                choose.append(t.getChooseId()+",");
            }
            //试题
            List<Topicsingle> list1 = (List<Topicsingle>) map.get(2);
            for (Topicsingle t:list1) {
                t = topicsingleService.addTopicsingle(t);
                topics.append(t.getTopicId()+",");
            }
            // 生成试卷
            Exampaper exampaper = new Exampaper();
            Course course = new Course();
            course.setCourseId((long) courseId);
            exampaper.setCourse(course);
            exampaper.setPaperchoose(choose+"");
            exampaper.setPapertopics(topics+"");
            exampaperDao.save(exampaper);
            return 1;
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public Page<Exampaper> getExampaperByPage(List<Long> courseId, int page, int size) {
        Pageable pageable = PageRequest.of(page-1,size);
        return exampaperDao.getExampaperByPage(courseId,pageable);
    }

    @Override
    public int countExampaperBypaperId(Integer paperId) {
        int count = 0;
        Exampaper exampaper = exampaperDao.findById(paperId).get();
        // 获取试题号
        String t = exampaper.getPapertopics();
        logger.info("topic:"+t);
        t = t.substring(0,t.length()-1);
        String[] t1 = t.split(",");
        for (int i = 0;i < t1.length;i++){
            logger.info("t1[]:"+t1[i]);
            logger.info("Score:"+topicsingleService.getTopicsingleByTopicId(t1[i]).getTopicScore());
            count += topicsingleService.getTopicsingleByTopicId(t1[i]).getTopicScore();
        }
        // 获取选择题号
        String c = exampaper.getPaperchoose();
        logger.info("topic:"+c);
        c = c.substring(0,c.length()-1);
        String[] c1 = c.split(",");
        for (int i = 0;i < c1.length;i++){
            count += topicmultService.getTopicmultById(c1[i]).getChooseScore();
        }
        logger.info("count:"+count);
        return count;
    }

    @Override
    public Exampaper getExampaperByPaperId(Integer paperId) {
        return exampaperDao.findById(paperId).get();
    }


    /**
     * 获取 某试卷的 所有试题信息
     *
     * @param paperId
     * @return
     */
    @Override
    public Map<Integer, Object> getTopicsByPaperId(Integer paperId) {
        //存 某试卷 的所有试题信息
        Map<Integer, Object> map = new HashMap<Integer, Object>();

        //存判断题1
        List<Topicsingle> list1 = new ArrayList<Topicsingle>();
        //存填空题2
        List<Topicsingle> list2 = new ArrayList<Topicsingle>();
        //存综合题3
        List<Topicsingle> list3 = new ArrayList<Topicsingle>();
        //存单选题4
        List<Topicmult> list4 = new ArrayList<Topicmult>();
        //存多选题5
        List<Topicmult> list5 = new ArrayList<Topicmult>();

        //根据paperId获取ExamPaper
        Exampaper exampaper = getExampaperByPaperId(paperId);
        //根据exampaper获取试题组
        String single = exampaper.getPapertopics();
        //去掉最后一个,
        single = single.substring(0, single.length() - 1);
        String sstr[] = single.split(",");
        for (int n = 0; n < sstr.length; n++) {
            //通过id获取选择题
            Topicsingle topicsingle = topicsingleService.getTopicsingleByTopicId(sstr[n]);
            //试题类型（判断题1、填空题2、综合题3）
            int type = topicsingle.getTopicType();
            if (type == 1) {
                list1.add(topicsingle);
            } else if (type == 2) {
                list2.add(topicsingle);
            } else if (type == 3) {
                list3.add(topicsingle);
            }
        }

        //根据exampaper获取试题组
        String mult = exampaper.getPaperchoose();
        //去掉最后一个,
        mult = mult.substring(0, mult.length()-1);
        String mstr[] = mult.split(",");
        for (int n = 0; n < mstr.length; n++) {
            //通过id获取选择题
            Topicmult topicmult = topicmultService.getTopicmultById(mstr[n]);
            //选择题类型（单选1/多选2）
            int type = topicmult.getChooseType();
            if (type == 1) {
                list4.add(topicmult);
            } else if (type == 2) {
                list5.add(topicmult);
            }
        }
        map.put(1, list1);
        map.put(2, list2);
        map.put(3, list3);
        map.put(4, list4);
        map.put(5, list5);
        return map;
    }

    /**
     * 获取 某试卷的 single试题信息
     *
     * @param paperId
     * @return
     */
    @Override
    public Map<Integer, List<Topicsingle>> getTopicsByPaperId1(Integer paperId) {
        //存 某试卷 的所有试题信息
        Map<Integer, List<Topicsingle>> map = new HashMap<Integer, List<Topicsingle>>();

        //存判断题1
        List<Topicsingle> list1 = new ArrayList<Topicsingle>();
        //存填空题2
        List<Topicsingle> list2 = new ArrayList<Topicsingle>();
        //存综合题3
        List<Topicsingle> list3 = new ArrayList<Topicsingle>();


        //根据paperId获取ExamPaper
        Exampaper exampaper = getExampaperByPaperId(paperId);
        //根据exampaper获取试题组
        String single = exampaper.getPapertopics();
        //去掉最后一个,
        single = single.substring(0, single.length() - 1);
        String sstr[] = single.split(",");
        for (int n = 0; n < sstr.length; n++) {
            //通过id获取选择题
            Topicsingle topicsingle = topicsingleService.getTopicsingleByTopicId(sstr[n]);
            //试题类型（判断题1、填空题2、综合题3）
            int type = topicsingle.getTopicType();
            if (type == 1) {
                list1.add(topicsingle);
            } else if (type == 2) {
                list2.add(topicsingle);
            } else if (type == 3) {
                list3.add(topicsingle);
            }
        }
        map.put(1, list1);
        map.put(2, list2);
        map.put(3, list3);

        return map;
    }

    /**
     * 获取 某试卷的 所有试题信息
     *
     * @param paperId
     * @return
     */
    @Override
    public Map<Integer, List<Topicmult>> getTopicsByPaperId2(Integer paperId) {
        //存 某试卷 的所有试题信息
        Map<Integer, List<Topicmult>> map = new HashMap<Integer, List<Topicmult>>();

        //存单选题4
        List<Topicmult> list4 = new ArrayList<Topicmult>();
        //存多选题5
        List<Topicmult> list5 = new ArrayList<Topicmult>();

        //根据paperId获取ExamPaper
        Exampaper exampaper = getExampaperByPaperId(paperId);


        //根据exampaper获取试题组
        String mult = exampaper.getPaperchoose();
        //去掉最后一个,
        mult = mult.substring(0, mult.length());
        String mstr[] = mult.split(",");
        for (int n = 0; n < mstr.length; n++) {
            //通过id获取选择题
            Topicmult topicmult = topicmultService.getTopicmultById(mstr[n]);
            //选择题类型（单选1/多选2）
            int type = topicmult.getChooseType();
            if (type == 1) {
                list4.add(topicmult);
            } else if (type == 2) {
                list5.add(topicmult);
            }
        }
        map.put(4, list4);
        map.put(5, list5);
        return map;
    }

    /**
     * 获取 某同学的某试卷所有试题信息及答案
     *
     * @param paperId
     * @return
     */
    @Override
    public Map<Integer, Object> getTopicsAndAnswers(Integer paperId, String userId, int examId) {
        //获取某同学的某份试卷的所有答题情况
        List<Answer> listAnswers = asi.allanswerList(examId, userId);

        //存 某试卷 的所有试题信息
        Map<Integer, Object> map = new HashMap<Integer, Object>();

        //存判断题1
        List<Topicsingle> list1 = new ArrayList<Topicsingle>();
        //存填空题2
        List<Topicsingle> list2 = new ArrayList<Topicsingle>();
        //存综合题3
        List<Topicsingle> list3 = new ArrayList<Topicsingle>();
        //存单选题4
        List<Topicmult> list4 = new ArrayList<Topicmult>();
        //存多选题5
        List<Topicmult> list5 = new ArrayList<Topicmult>();

        //根据paperId获取ExamPaper
        Exampaper exampaper = getExampaperByPaperId(paperId);
        //根据exampaper获取试题组
        String single = exampaper.getPapertopics();
        //去掉最后一个,
        single = single.substring(0, single.length() - 1);
        String sstr[] = single.split(",");

        for (int n = 0; n < sstr.length; n++) {
            //通过id获取选择题
            Topicsingle topicsingle = topicsingleService.getTopicsingleByTopicId(sstr[n]);
            for (Answer answer : listAnswers) {
                //试题类型（判断题1、填空题2、综合题3）
                if (answer.getTopicId().equals(sstr[n])) {
                    topicsingle.setAnswerContent(answer.getAnswerContent());
                    topicsingle.setScore(answer.getSocre());
                }
            }
            int type = topicsingle.getTopicType();
            if (type == 1) {
                list1.add(topicsingle);
            } else if (type == 2) {
                list2.add(topicsingle);
            } else if (type == 3) {
                list3.add(topicsingle);
            }

        }

        //根据exampaper获取试题组
        String mult = exampaper.getPaperchoose();
        //去掉最后一个,
        mult = mult.substring(0, mult.length()-1);
        String mstr[] = mult.split(",");

        for (int n = 0; n < mstr.length; n++) {
            //通过id获取选择题
            Topicmult topicmult = topicmultService.getTopicmultById(mstr[n]);
            for (Answer answer : listAnswers) {
                if (answer.getTopicId().equals(mstr[n])) {
                    topicmult.setAnswerContent(answer.getAnswerContent());
                    topicmult.setScore(answer.getSocre());
                }
            }
            //选择题类型（单选1/多选2）
            int type = topicmult.getChooseType();
            if (type == 1) {
                list4.add(topicmult);
            } else if (type == 2) {
                list5.add(topicmult);
            }
        }
        map.put(1, list1);
        map.put(2, list2);
        map.put(3, list3);
        map.put(4, list4);
        map.put(5, list5);
        return map;
    }
}
